﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace MyMovies
{
    [XmlRootAttribute("Parameters", Namespace = "http://www.mauro.rogledi.it", IsNullable = false)]
    [Serializable()]
    public class Parameters : SaveSerializable
    {
        //public List<PairsParameters> Pairs;

        //[XmlArray("IncludeFilter")]
        //[XmlArrayItem("Filter")]
        //public List<string> IncludeFilter;

        public string ShowScanPath;
        public string ScanPath;

        public static Parameters Load(string filename)
        {
            return (Parameters)SaveSerializable.Load(filename, typeof(Parameters));
        }

        public void Save(string filename)
        {
            Save(filename, this.GetType());
        }
    }

    #region SaveSerializable

    [Serializable()]
    public abstract class SaveSerializable
    {
        public void Save(string filename, Type type)
        {
            TextWriter stream = new StreamWriter(filename);
            XmlSerializer xmlSer = new XmlSerializer(type);
            xmlSer.UnknownAttribute += new XmlAttributeEventHandler(xmlSer_UnknownAttribute);
            xmlSer.UnknownNode += new XmlNodeEventHandler(xmlSer_UnknownNode);
            xmlSer.Serialize(stream, this);

            stream.Close();
        }

        private void xmlSer_UnknownNode(object sender, XmlNodeEventArgs e)
        {
            throw new NotImplementedException();
        }

        private void xmlSer_UnknownAttribute(object sender, XmlAttributeEventArgs e)
        {
            throw new NotImplementedException();
        }

        public static SaveSerializable Load(string filename, Type type)
        {
            if (!File.Exists(filename)) return null;
            Stream stream = null;
            try
            {
                stream = File.Open(filename, FileMode.Open);
                XmlSerializer xmlSer = new XmlSerializer(type);

                Parameters p = (Parameters)xmlSer.Deserialize(stream);

                return p;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            finally
            {
                stream.Close();
            }
            return null;
        }
    }

    #endregion SaveSerializable
}